package com.zyj.concurrency;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class CyclicBarrierTest {

    private static final Integer SIZE = 10;
    private static final AtomicInteger counter = new AtomicInteger();
    private static final CyclicBarrier cyclicBarrier = new CyclicBarrier(SIZE);
    private static final ExecutorService threadPool = Executors.newFixedThreadPool(SIZE);

    public static void main(String[] args) {

        for (int i = 0; i < SIZE; i++){
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 模拟准备时间
                        System.out.println(counter.getAndIncrement() + "号选手已就绪。。。");
                        // 当前线程进入等待状态
                        cyclicBarrier.await();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        // 当所有线程进入等待状态时，CyclicBarrier计数为零，所有线程一起执行
        System.out.println("比赛开始。。。");

        threadPool.shutdown();
    }

}
